;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Stock.ReturnIn", [])
        .controller("ReturnInCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService) {
            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.submitted = false;
            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.billPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.orderCondition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.dataList = [];
            $scope.returnApplyList = [];
            $scope.detailInfo = {};
            $scope.steps = {
                curStep: 0,
                list: [{name: '选择退货申请单'}, {name: '生成退货入库单'}]
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/returnIn/export"),
                sectionParam: {returnInIds: []},
                allUrl: ybHttp.RequestUrl("device", "/returnIn/exportAll")
            };
            $scope.tableConfig = {
                fixedWidth: 300,
                scrollWidth: 1050,
                tableCol: [
                    {
                        type: "",
                        name: "退货入库单号",
                        dataField: "returnNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单据类型",
                        dataField: "billTypeName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调入仓库",
                        dataField: "warehouseCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "入库状态",
                        dataField: "statusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "synSap",
                        name: "过账状态",
                        dataField: "postingStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewSapError",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP退货订单号",
                        dataField: "sapOrderNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "",
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 260,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.returnApplyTbConf = {
                scrollWidth: 510,
                tableCol: [
                    {
                        type: "",
                        name: "退货申请单号",
                        dataField: "applyNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购公司",
                        dataField: "purchaseOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 80,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.newTbConf = {
                scrollWidth: 940,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        width: 120,
                        dataField: "stockLocation",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货总数",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已申请入库数量",
                        width: 120,
                        dataField: "returnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可入库数量",
                        width: 100,
                        dataField: "canInQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库数量",
                        width: 100,
                        dataField: "thisReturn",
                        input: true,
                        inputType: "num"
                    }
                ]
            };
            $scope.editTbConf = {
                scrollWidth: 1000,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        width: 120,
                        dataField: "stockLocation",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货总数",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已申请入库数量",
                        width: 120,
                        dataField: "returnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "可入库数量",
                        width: 100,
                        dataField: "canInQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库数量",
                        width: 100,
                        dataField: "thisReturn",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "实际入库数量",
                        width: 120,
                        dataField: "inQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    }
                ]
            };
            $scope.detailTbConf = {
                scrollWidth: 1060,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "默认储位",
                        width: 120,
                        dataField: "stockLocation",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 100,
                        dataField: "priceSchemeName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "price",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货总数",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已申请入库数量",
                        width: 120,
                        dataField: "returnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库数量",
                        width: 100,
                        dataField: "thisReturn",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "实际入库数量",
                        width: 120,
                        dataField: "inQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    }
                ]
            };
            $scope.inTbConf = {
                scrollWidth: 1100,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "退货总数",
                        width: 100,
                        dataField: "applyQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已申请入库数量",
                        width: 120,
                        dataField: "returnQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库数量",
                        width: 100,
                        dataField: "thisReturn",
                        input: false,
                        inputType: "num"
                    },
                    {
                        name: "储位",
                        width: 150,
                        dataField: "locationCode",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "statusShow",
                        input: false,
                        inputType: ""
                    }
                ]
            };
            $scope.tabFlag = {};
            var sortParam = "";
            var sortFiled = {};

            var btnPermissionCode = {
                returnInAdd: window.ActionCode.returnInAdd,
                returnInEdit: window.ActionCode.returnInEdit,
                returnInDel: window.ActionCode.returnInDel,
                returnInIn: window.ActionCode.returnInIn,
                returnInExport: window.ActionCode.returnInExport,
                returnInPrint: window.ActionCode.returnInPrint,
                mandatoryFinish: window.ActionCode.returnInMandatoryFinish,
                returnInPosting: window.ActionCode.returnInPosting,
                returnInPostingCancel: window.ActionCode.returnInPostingCancel
            };

            $scope.btnPermission = {
                returnInAdd: true,
                returnInEdit: true,
                returnInDel: true,
                returnInIn: true,
                returnInExport: true,
                returnInPrint: true,
                mandatoryFinish: true,
                returnInPosting: true,
                returnInPostingCancel: true
            };

            var materialList = [];

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.detailInfo = {};
                $scope.steps.curStep = 0;
                $scope.tabFlag = {};
                materialList = [];
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allChecked: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.returnInIds = [];
                var service = "device";
                var reqUrl = "/returnIn/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createTime,"yyyy-MM-dd HH:mm:ss");
                        item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                        item.postingStateShow = $filter("ProgressStatus")(item.postingState, "postingState");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                // return;
                if (!config[index].toSort) {
                    return;
                }
                var sortType = ybWidget.ToSort(config, index);
                sortFiled = config[index];
                sortParam = sortFiled.sortField + " " + sortType;
                getDataList(1);
            };

            function clearSortParam() {
                sortParam = "";
                if (angular.isDefined(sortFiled.sortType)) {
                    sortFiled.sortType = ""
                }
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index;
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "viewSapError":
                        viewSapError(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {seller: true};
            };

            function geBillIds() {
                $scope.exportParam.sectionParam.returnInIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.returnInIds.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
                geBillIds();
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                geBillIds();
            };

            $scope.add = function () {
                $scope.tabFlag.type = 0;
                getReturnApply(1);
                $scope.changeTab(1);
            };
            function getReturnApply(curPage) {
                var service = "device";
                var reqUrl = "/returnApply/list";
                var param = {};
                param.pageSize = $scope.billPageInfo.pageSize;
                if (!!curPage) {
                    $scope.billPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.billPageInfo.curPage;
                param.filters = {};
                param.filters.ifReturn = 1;
                param.filters.purchaseOrgName = $scope.orderCondition.purchaseOrgName;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate,"yyyy-MM-dd HH:mm:ss");
                    });
                    $scope.billPageInfo.totalRows = resp.value.total;
                    $scope.billPageInfo.totalPages = resp.value.pages;
                    $scope.returnApplyList = resp.value.list;
                });
            }

            $scope.orderSearch = function () {
                getReturnApply();
            };

            $scope.selBill = function (item) {
                $scope.steps.curStep = 1;
                $scope.detailInfo.returnInAddDetailVOs = [];
                ybHttp.Get('device', '/returnApply/item', {id: item.id}).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.billTypeName = "退货入库";
                    $scope.detailInfo.applyNo = resp.value.applyNo;
                    $scope.detailInfo.createId = $scope.curUser.userId;
                    $scope.detailInfo.createName = $scope.curUser.name;
                    $scope.detailInfo.createPartId = $scope.curUser.deptId;
                    $scope.detailInfo.createPartName = $scope.curUser.deptName;
                    $scope.detailInfo.createDate = +new Date();
                    $scope.detailInfo.inLocation = "";
                    $scope.detailInfo.remark = "";
                    angular.forEach(resp.value.returnApplyDetailVOs, function (item) {
                        var materielItem = {};
                        materielItem.id = item.id;
                        materielItem.materialsNo = item.materialsNo;
                        materielItem.materialsDes = item.materialsDes;
                        materielItem.unit = item.unit;
                        materielItem.applyQty = item.applyQty;
                        materielItem.returnQty = item.returnQty;
                        materielItem.canInQty = ybWidget.Minus(item.applyQty, materielItem.returnQty);
                        materielItem.thisReturn = materielItem.canInQty;
                        materielItem.priceSchemeId = item.priceSchemeId;
                        materielItem.priceSchemeName = item.priceSchemeName;
                        materielItem.price = item.price;
                        materielItem.stockLocationList = item.stockLocationList;
                        $scope.detailInfo.returnInAddDetailVOs.push(materielItem);
                    });
                    materialList = angular.copy($scope.detailInfo.returnInAddDetailVOs);

                });
            };

            $scope.delData = function (delType, billId) {
                var service = "device";
                var reqUrl = "/returnIn/remove";
                var billIds = [];

                if (delType === "single") {
                    billIds.push(billId);
                }

                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            billIds.push($scope.dataList[i].id);
                        }
                    }
                }

                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, billIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector().then(function (data) {
                    if (!!$scope.detailInfo.warehouseCode && (data.warehouseCode !== $scope.detailInfo.warehouseCode)) {
                        $scope.detailInfo.inArea = "";
                        $scope.detailInfo.sapInArea = "";
                        angular.forEach(materialList, function (item) {
                            item.stockLocation = "";
                        });
                        $scope.detailInfo.returnInAddDetailVOs = materialList;
                    }
                    $scope.detailInfo.warehouseCode = data.warehouseCode;
                    filterMaterial();
                })
            };

            $scope.clearWarehouse = function () {
                $scope.detailInfo.warehouseCode = "";
                $scope.detailInfo.inArea = "";
                $scope.detailInfo.sapInArea = "";
                angular.forEach(materialList, function (item) {
                    item.stockLocation = "";
                });
                $scope.detailInfo.returnInAddDetailVOs = materialList;
            };

            function filterMaterial() {
                var warehouseCode = $scope.detailInfo.warehouseCode;
                var areaCode = $scope.detailInfo.inArea;
                for (var i =0, len = $scope.detailInfo.returnInAddDetailVOs.length; i < len; i++) {
                    if (!!$scope.detailInfo.returnInAddDetailVOs[i].stockLocationList && $scope.detailInfo.returnInAddDetailVOs[i].stockLocationList.length > 0) {
                        for (var j =0, lenJ = $scope.detailInfo.returnInAddDetailVOs[i].stockLocationList.length; j < lenJ; j++) {
                            var mWarehouseCode = $scope.detailInfo.returnInAddDetailVOs[i].stockLocationList[j].warehouseCode;
                            var mLocationCode = $scope.detailInfo.returnInAddDetailVOs[i].stockLocationList[j].locationCode;
                            var mAreaCode = $scope.detailInfo.returnInAddDetailVOs[i].stockLocationList[j].areaCode;
                            if (warehouseCode === mWarehouseCode) {
                                if(!!areaCode && areaCode!==mAreaCode){
                                    $scope.detailInfo.returnInAddDetailVOs[i].stockLocation = '';
                                    continue;
                                }
                                $scope.detailInfo.returnInAddDetailVOs[i].stockLocation = mLocationCode;
                                break;
                            }
                        }
                    }
                }
            }

            $scope.selectArea = function () {
                if (!$scope.detailInfo.warehouseCode) {
                    ybWidget.ShowToaster('error', '请选择调入仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.detailInfo.warehouseCode;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.detailInfo.inArea = data.areaCode;
                    $scope.detailInfo.sapInArea = data.sapCode;
                    filterMaterial();
                })
            };

            $scope.clearArea = function () {
                $scope.detailInfo.inArea = "";
                $scope.detailInfo.sapInArea = "";
                $scope.detailInfo.returnInAddDetailVOs = materialList;
            };

            function getDetail(billId) {
                var service = "device";
                var reqUrl = "/returnIn/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.editData = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.detailInfo = data;
                    $scope.detailInfo.returnInAddDetailVOs = $scope.detailInfo.returnInDetailVOs;
                    angular.forEach($scope.detailInfo.returnInAddDetailVOs, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                        item.canInQty = ybWidget.Plus(ybWidget.Minus(item.applyQty, item.returnQty), item.thisReturn);
                    });
                    materialList = angular.copy($scope.detailInfo.returnInAddDetailVOs);
                    $scope.changeTab(2);
                })
            };

            function viewDetail(item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.returnInDetailVOs, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                    });
                    $scope.changeTab(3);
                })
            }

            function viewSapError(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            $scope.checkQty = function (item) {
                item.qtyErr = false;
                if (item.thisReturn === "") {
                    item.qtyErr = true;
                    item.qtyErrMsg = "入库数量不能为空";
                    return;
                }
                if(item.thisReturn>99999.999){
                    item.thisReturn=99999.999;
                }
                if (parseFloat(item.thisReturn) > parseFloat(item.canInQty)) {
                    item.qtyErr = true;
                    item.qtyErrMsg = "入库数量不能大于可入库数量";
                }
                if (parseFloat(item.thisReturn) < parseFloat(item.inQty)) {
                    item.qtyErr = true;
                    item.qtyErrMsg = "入库数量不能小于实际入库数量";
                }
            };

            function checkListValid() {
                var isValid = true;
                for (var i = 0, len = $scope.detailInfo.returnInAddDetailVOs.length; i < len; i++) {
                    if ($scope.detailInfo.returnInAddDetailVOs[i].thisReturn === "") {
                        isValid = false;
                        $scope.detailInfo.returnInAddDetailVOs[i].qtyErr = true;
                        $scope.detailInfo.returnInAddDetailVOs[i].qtyErrMsg = "入库数量不能为空";
                        break;
                    }
                    if (parseInt($scope.detailInfo.returnInAddDetailVOs[i].thisReturn) > parseInt($scope.detailInfo.returnInAddDetailVOs[i].canInQty)) {
                        isValid = false;
                        $scope.detailInfo.returnInAddDetailVOs[i].qtyErr = true;
                        $scope.detailInfo.returnInAddDetailVOs[i].qtyErrMsg = "入库数量不能大于可入库数量";
                        break;
                    }
                    if (parseInt($scope.detailInfo.returnInAddDetailVOs[i].thisReturn) < parseInt($scope.detailInfo.returnInAddDetailVOs[i].inQty)) {
                        isValid = false;
                        $scope.detailInfo.returnInAddDetailVOs[i].qtyErr = true;
                        $scope.detailInfo.returnInAddDetailVOs[i].qtyErrMsg = "入库数量不能小于实际入库数量";
                        break;
                    }
                }
                return isValid;
            }

            $scope.mandatoryFinish = function (billNo, billId, materialsNo) {
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/returnIn/manualFinish";
                    var param = {
                        billNo: billNo,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!billId) {
                            getDetail(billId).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.detailInfo = data;
                                angular.forEach($scope.detailInfo.returnInDetailVOs, function (item) {
                                    item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                                });
                            });
                        }
                        getDataList();
                    });
                }, function () {
                });
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = checkListValid();
                if (!listValid) {
                    return;
                }
                var service = "device";
                var reqUrl = "/returnIn/add";

                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/returnIn/update";
                }
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };

            $scope.inbound = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.detailInfo = data;
                    angular.forEach($scope.detailInfo.returnInDetailVOs, function (item) {
                        item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                    });
                    $scope.changeTab(4);
                });
            };

            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "ReturnIn"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.detailInfo.warehouseCode
                };

                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };

            $scope.inboundSubmit = function () {
                var service = "device";
                var reqUrl = "/warehouseInboundRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                var errorCount = 0;
                param.headerInfo.businessOrder = $scope.detailInfo.returnNo;
                angular.forEach($scope.detailInfo.returnInDetailVOs, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialsNo;
                    listRow.warehouseCode = item.warehouseCode;
                    listRow.areaCode = item.areaCode;
                    listRow.locationCode = item.locationCode;
                    item.locationErr = false;
                    if((item.status === 0 || item.status === 1) && !item.locationCode){
                        item.locationErr = true;
                        errorCount++;
                    }
                    param.detailList.push(listRow);
                });
                if(errorCount> 0){
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.prevStep = function () {
                $scope.steps.curStep = 0;
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.posting = function (id, sapType) {
                var service = "device";
                var reqUrl = "/returnIn/sapPost";
                if(sapType === 2){
                    reqUrl = "/returnIn/sapRemove";
                }
                var param = {};
                param.id = id;
                var msg = sapType===1?"确定要过账吗？":"确定要取消过账吗？";
                ybWidget.ShowMessage(msg, MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
